package com.settlement.system.common.util.common;

import com.settlement.system.common.constant.StandardConstant;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.mapper.security.userdetails.SysUserDetails;
import com.settlement.system.model.entity.common.BaseModel;
import com.settlement.system.model.entity.common.SystemUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @author author
 */
@Slf4j
public class SystemUserUtil {

    private static ThreadLocal<SystemUser> localUser = new ThreadLocal<SystemUser>();

    public static SystemUser getSystemUser(){
        return localUser.get();
    }

    /**
     * 获取当前登陆用户信息
     *
     * @param request
     * @return 当前登陆用户信息
     */
    public static void setSystemUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        SystemUser systemUser = null;
        String userCode = (String) session.getAttribute(StandardConstant.USER_SESSION_ID);
        try {
            systemUser =(SystemUser) session.getAttribute(StandardConstant.USER_SESSION);
            localUser.set(systemUser);
        }catch (Exception e){
            log.error("获取登录用户异常",e);
            localUser.remove();
        }
    }

    /**
     * 设置默认值
     * @param model
     */
    public static void setDefualt(BaseModel model){
        SysUserDetails user = SecurityUtils.getUser();;
        if(StringUtils.isEmpty(model.getId())){
            model.setId(UUID.randomUUID().toString().replace("-", ""));
            model.setCreateTime(new Date());

            if(user != null && !StringUtils.isEmpty(user.getUsername())){
                model.setCreateUser(user.getUsername());
            }
        }
        if(user != null){
            model.setUpdateUser(user.getUsername());
        }
        model.setUpdateTime(new Date());
    }
}
